package org.example.exampreparationtreasure.controller;

import org.example.exampreparationtreasure.common.ApiResponse;
import org.example.exampreparationtreasure.common.BusinessException;
import org.example.exampreparationtreasure.common.CommonResultStatus;
import org.example.exampreparationtreasure.config.JwtConfig;
import org.example.exampreparationtreasure.model.entity.Question;
import org.example.exampreparationtreasure.model.vo.PreferenceRequest;
import org.example.exampreparationtreasure.model.vo.RecommendationHistoryResponse;
import org.example.exampreparationtreasure.model.vo.StudyPlanResponse;
import org.example.exampreparationtreasure.service.RecommendationService;
import org.example.exampreparationtreasure.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/v1/recommendations")
@RequiredArgsConstructor
public class RecommendationController {
    private final RecommendationService recommendationService;
    private final JwtUtil jwtUtil;
    private final JwtConfig jwtConfig;

    /**
     * 获取推荐题目 - 从token获取用户ID
     */
    @GetMapping("/questions")
    public ApiResponse<List<Question>> getRecommendedQuestions(
            @RequestParam(required = false) String includeCategoryIds,
            @RequestParam(required = false) String difficultyLevel,
            @RequestParam(required = false, defaultValue = "10") Integer size,
            HttpServletRequest request) {

        Long userId = getUserIdFromToken(request);

        // 处理分类过滤参数
        List<Long> categoryIds = null;
        if (includeCategoryIds != null && !includeCategoryIds.trim().isEmpty()) {
            try {
                categoryIds = Arrays.stream(includeCategoryIds.split(","))
                        .map(String::trim)
                        .map(Long::valueOf)
                        .collect(Collectors.toList());
            } catch (NumberFormatException e) {
                throw new BusinessException(CommonResultStatus.PARAM_ERROR, "分类ID格式错误");
            }
        }

        List<Question> result;
        if (difficultyLevel != null && !difficultyLevel.trim().isEmpty()) {
            // 使用带难度过滤的推荐
            result = recommendationService.getRecommendedQuestionsWithPreference(
                    userId, categoryIds, difficultyLevel, size);
        } else {
            // 使用普通推荐
            result = recommendationService.getRecommendedQuestions(userId, categoryIds, size);
        }

        return ApiResponse.ok(result);
    }

    /**
     * 生成学习计划 - 从token获取用户ID
     */
    @GetMapping("/study-plan")
    public ApiResponse<StudyPlanResponse> getStudyPlan(HttpServletRequest request) {
        Long userId = getUserIdFromToken(request);
        StudyPlanResponse studyPlan = recommendationService.generateStudyPlan(userId);
        return ApiResponse.ok(studyPlan);
    }

    /**
     * 更新推荐偏好 - 从token获取用户ID
     */
    // Controller
    @PutMapping("/preference")
    public ApiResponse<PreferenceRequest> updateRecommendationPreference(
            @RequestBody PreferenceRequest preferenceRequest,
            HttpServletRequest request) {
        Long userId = getUserIdFromToken(request);
        recommendationService.updateUserPreference(userId, preferenceRequest);
        return ApiResponse.ok(preferenceRequest); // 改为回显
    }

    /**
     * 获取推荐历史 - 从token获取用户ID
     */
    @GetMapping("/history")
    public ApiResponse<RecommendationHistoryResponse> getRecommendationHistory(HttpServletRequest request) {
        Long userId = getUserIdFromToken(request);
        RecommendationHistoryResponse history = recommendationService.getRecommendationHistory(userId);
        return ApiResponse.ok(history);
    }

    /**
     * 从token中获取用户ID
     */
    private Long getUserIdFromToken(HttpServletRequest request) {
        String headerName = jwtConfig.getHeader();
        String authHeader = request.getHeader(headerName);
        
        if (authHeader == null || authHeader.isEmpty()) {
            throw new BusinessException(CommonResultStatus.UNAUTHORIZED, "未提供令牌");
        }

        String token;
        if (authHeader.startsWith("Bearer ")) {
            token = authHeader.substring(7); // 去掉"Bearer "（7个字符）
        } else {
            token = authHeader;
        }

        try {
            // 验证token是否过期
            if (jwtUtil.isTokenExpired(token)) {
                throw new BusinessException(CommonResultStatus.UNAUTHORIZED, "令牌已过期");
            }
            
            // 从token中获取用户ID
            Long userId = jwtUtil.getUserIdByToken(token);
            if (userId == null) {
                throw new BusinessException(CommonResultStatus.UNAUTHORIZED, "无法从令牌中获取用户ID");
            }
            
            return userId;
        } catch (Exception e) {
            throw new BusinessException(CommonResultStatus.UNAUTHORIZED, "无效令牌");
        }
    }
}